<script setup>
import { ref, reactive, onMounted, toRefs, watch } from 'vue'
import { ElMessage } from 'element-plus'

import { store } from '@/js/store.js';
/**
 * 素材中心
 */

const props = defineProps({
    hashName: String,
    modeParams: Object,
    type: {
        type: Number,
        default: 0
    },
    xuanze: Boolean,
    formData: {
        type: Object,
        default: () => { }
    }
});
//需要响应式时使用toRefs
const { modeParams, hashName, formData } = toRefs(props);
//向父级传递消息
const emits = defineEmits(['tohost'])
function sendEmit() {
    emits('tohost', ...arguments);
}
//组件暴露自己的属性
//defineExpose({
//    init,
//});

const rowsData = ref([
    { id: 1, name: '图片1', originName:'pic1.jpg', url: '/images/pic1.jpg' },
    { id: 2, name: '图片2', originName:'pic2.jpg', url: '/images/pic2.jpg' },
    { id: 3, name: '图片3', originName:'pic3.jpg', url: '/images/pic3.jpg' },
    { id: 4, name: '图片4', originName:'pic4.jpg', url: '/images/pic4.jpg' },
    { id: 5, name: '文件1', originName:'doc1.jpg', url: '/images/--.doc' }
]);
const listMeta = reactive({ page: 1, size: 10 })
const search = ref({ name: '', type: 1 });

async function getList(_page) {
    if (_page) {
        listMeta.page = _page;
    }
    try {
        //const result = await api.get({ ...listMeta, ...search.value });
        // rowsData.value = result.data;
        // listMeta.count = result.meta.count;
        // listMeta.total = Math.ceil(result.meta.count / listMeta.size);
    } catch (error) {
    }
}

//添加、修改
const dialog = ref(false);
const dialogTitle = ref('');
const queryFormRef = ref()
const fileSelect = ref([])
const materialType = [
    { label: '图片', value: 1 },
    { label: '文档', value: 2 },
    { label: '音频', value: 3 },
    { label: '视频', value: 4 }
]

const handleQuery = () => {
    getList(1);
}
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value.resetFields()
    getList(1);
}

const handleTabClick = (tab) => {
    search.value.type = tab.paneName
    handleQuery()
}

const upfileSize = 2048;
function beforeUpload(file) {
    if (file.size / 1024 > upfileSize) {
        ElMessage({ message: '文件大小限制' + (upfileSize >= 1024 ? (upfileSize / 1024) + 'MB' : upfileSize + 'KB'), type: 'warning' })
        return false;
    }
    return true;
}

async function handleUpload(options) {
    try {
        // const result = await api.requestUpload(options)
        // result && resetQuery()
    } catch (err) {
        console.error(err);
        // 处理上传错误
    }
}

function sindXuan() {
    var arr = []
    rowsData.value.forEach(item => {
        if(fileSelect.value.find(ev=> ev == item.id)){
            arr.push(item)
        }
    })
    modeParams.value && onXuanze(arr, modeParams.value)
    emits('tohost', arr);
}

//素材中心的选择：
const onXuanze = (data, params) => {
    const len = params.upfiles.length;
    if (params.isEdit > -1) {
        data[0].sort = params.isEdit + 1
        params.upfiles[params.isEdit] = data[0];
        params.isEdit = -1;
    } else if (len + data.length <= params.maxnum) {
        data.forEach((item, index) => {
            item.sort = len + index + 1
        })
        params.upfiles.push(...data);
    } else {
        ElMessage.warning('文件数量限制' + params.maxnum + '个')
    }
    params.closeDialog()
}

onMounted(() => {
    getList(1);
})

//监听变化
watch(() => props.formData, (newVal, oldValue) => {
    if (newVal && newVal.id) {
        //find()
    }
})


</script>
<template>
    <div class="warrper">
        <el-card>
            <el-tabs v-model="search.type" @tab-click="handleTabClick">
                <el-tab-pane v-for="item in materialType" :key="item.value" :label="item.label" :name="item.value" />
            </el-tabs>
            <el-form ref="queryFormRef" :inline="true" :model="search" label-width="68px">
                <el-form-item label="素材名称" prop="name">
                    <el-input v-model="search.name" clearable placeholder="请输入素材名称"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                    <el-button>搜索</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                    <el-upload :http-request="handleUpload" :before-upload="beforeUpload" :show-file-list="false">
                        <el-button type="primary">上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-card>
        <ul class="xuanlist thumbnail-style">
            <label v-for="(item, index) in rowsData" :key="index">
                <div class="img"><img :src="item.url" @error="$event.target.src = '/images/icon-file.svg'" /></div>
                <h4 class="ellipsis"><input type="checkbox" :value="item.id" v-model="fileSelect" /> {{ item.originName
                    }}</h4>
                <h5 class="ellipsis"><a @click="editRow(item)" v-if="!xuanze">修改</a> {{ item.name }}</h5>
                <div></div>
            </label>
        </ul>

        <el-button v-if="xuanze" type="primary" @click="sindXuan">确认选择</el-button>

        <!-- <div class="pagination">
            <el-pagination background layout="total, prev, pager, next" :current-page="listMeta.page" :total="listMeta.count" :page-size="listMeta.size" class="right"
            @current-change="getList"></el-pagination>
            <hr>
        </div> -->
    </div>
</template>

<style scoped>
.xuanlist{
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap:wrap;
    width: 100%;
    margin: 10px auto;
}
.xuanlist h4{
    display: block; margin: 5px 0 0;padding: 0;
    font-size: 13px; line-height: 1.4;max-height: 22px;overflow: hidden;
}
.xuanlist span{float: right;font-size: 12px; line-height: 1;color: #999; }
.xuanlist h5{display: block;margin: 0;padding: 0;font-size: 12px;line-height: 1.4;color: #999;}

/* 缩略图样式 */
.thumbnail-style {
    list-style-type: none;
    padding: 0;
    display: flex;
    flex-wrap: wrap;
}
.thumbnail-style label {
    margin: 0 10px 46px;
    width: 100px;
    height: 100px;
    background-color: #f2f2f2;
    border: 1px solid #ddd;
}
.thumbnail-style label.active{box-shadow: rgba(0, 0, 0, 0.2) 0 4px 12px;border-color: dodgerblue;}
.thumbnail-style label .img{width: 100%;height: 100%;overflow: hidden;}
.thumbnail-style label img{width: 100%;height: 100%;}
</style>